package com.elitecrm.webchat.tpi;

import com.elite.ffmpegshell.OpusUtils;
import com.elitecrm.webchat.config.Config;
import com.elitecrm.webchat.util.FileUtil;
import com.elitecrm.webchat.util.StringUtil;
import com.elitecrm.webchat.util.VoiceUtil;
import com.elitecrm.webchat.util.file.FileOperateResult;
import com.elitecrm.webchat.util.voice.VoiceOperateResult;
import com.elitecrm.webchat.util.voice.VoiceOperator;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.DatatypeConverter;
import java.net.URL;

/**
 * @projectName: ngsapitask-hst
 * @package: com.elitecrm.webchat.tpi
 * @className: TpiLogic
 * @author: LiJT
 * @description: TODO
 * @date: 2023-06-01 17:26
 * @version: 1.0
 */
public class TpiLogic {
    private static final Logger log = LoggerFactory.getLogger(TpiLogic.class);

    public static TpiMessageHandleResult handleVoiceMessage(String voiceData, String voiceUri, int voiceLength, String voiceId, String voiceType) throws Exception {
        TpiMessageHandleResult thr = new TpiMessageHandleResult();
        byte[] voiceBytes;
        if (!StringUtils.isEmpty(voiceData)) {
            voiceBytes = DatatypeConverter.parseBase64Binary(voiceData);
            if (!"mp3".equals(voiceType)) {
                voiceBytes = VoiceUtil.convertAmrToMp3(voiceBytes);
            }
        } else {
            if (StringUtils.isEmpty(voiceUri)) {
                thr.setCode(-14);
                thr.setMessage("No voiceData or voiceUri found.");
                return thr;
            }

            URL source = new URL(voiceUri);
            voiceBytes = IOUtils.toByteArray(source);
            if (!"mp3".equals(voiceType)) {
                voiceBytes = VoiceUtil.convertAmrToMp3(voiceBytes);
            }
        }

        String fileName = voiceId + ".mp3";
        FileOperateResult ur = FileUtil.saveFile(voiceBytes, fileName);
        if (ur.isSuccess()) {
            String voiceDom = "";
            if (voiceLength == 0) {
                voiceLength = OpusUtils.getOpusDuration(fileName);
            }
            log.debug("Save voice file " + fileName + " successful. " + "voiceLength:" + voiceLength);
            if (TpiService.getInstance() != null && TpiService.getInstance().isCompatibleMode()) {
                voiceDom = "<a href='javascript:void(0)' onclick='playSound(\"" + ur.getUrl() + "\");return false;'>[ 语音 " + voiceLength + "s ]</a>";
            } else {
                voiceDom = "<div class='message-voice' data-length='" + voiceLength + "' data-url='" + ur.getUrl() + "' data-name='" + voiceId + "'></div>";
            }

            VoiceOperator vo = Config.getInstance().getVoiceOperator();
            if (null != vo) {
                VoiceOperateResult vors = vo.onRecognition(voiceData, voiceUri, "", voiceType, voiceLength + "");
                String recognition = vors.getRecognition();
                if (StringUtil.isNotNull(recognition)) {
                    voiceDom = voiceDom + "<div class='wechat-voice-recognition'>" + recognition + "</div>";
                }
            }

            thr.setResult(voiceDom);
        } else {
            log.error("Upload file failed: " + ur.getMessage());
            thr.setCode(-23);
            thr.setMessage(ur.getMessage());
        }

        return thr;
    }
}
